package com.soecode.lyf.config;

import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.soecode.lyf.dto.ResponseData;
import com.soecode.lyf.dto.Result;

import net.sf.json.JSONObject;

public class TokenInterceptor implements HandlerInterceptor{
	public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception arg3)
            throws Exception {
    }
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler, ModelAndView model) throws Exception {
    }
	//拦截每个请求
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        ResponseData responseData = ResponseData.ok();
        String token = request.getParameter("token");
        //token不存在
        System.out.println("收到的token"+token);
        if(null != token) {
        	DecodedJWT login = JWTUtils.verifyToken(token);
            String loginId = request.getParameter("userid"); // 收到Id
            String verifyId = login.getClaim("id").asString(); // 解密TOKEN中的id
           // System.out.println("收到的id"+loginId+"收到的token"+token);
            String exp = null;
            //解密token后的loginId与用户传来的loginId不一致，一般都是token过期
            if(null != loginId && null != login) {
                if(verifyId.equals(loginId)) {
                    return true;
                }else{
                	 responseData = ResponseData.forbidden();
                     responseMessage(response, response.getWriter(), responseData);
                    return false;
                }
            }else{
            	 responseData = ResponseData.forbidden();
                 responseMessage(response, response.getWriter(), responseData);
                return false;
            }
        }
        else{
        	 responseData = ResponseData.forbidden();
             responseMessage(response, response.getWriter(), responseData);
            return false;
        }
    }
    private void responseMessage(HttpServletResponse response, PrintWriter out, ResponseData responseData) {
    	responseData = ResponseData.forbidden();
        response.setContentType("application/json; charset=utf-8");  
        JSONObject obj=JSONObject.fromObject(responseData);
        out.print(obj.toString());
        out.flush();
        out.close();
    }
}
